import re
import time
from flask import request
from flask_restful import abort
from flask_login import current_user, login_user
from funcy import project
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.exc import IntegrityError
from funcy import partial
from redash import models, limiter
from redash.permissions import (
    require_permission,
    require_admin_or_owner,
    is_admin_or_owner,
    require_permission_or_owner,
    require_admin_default,
)
from redash.handlers.base import (
    BaseResource,
    require_fields,
    get_object_or_404,
    paginate,
    order_results as _order_results,
)

from redash.authentication.account import (
    invite_link_for_user,
    send_invite_email,
    send_password_reset_email,
    send_verify_email,
)
from redash.settings import parse_boolean
from redash import settings

class ContractApplyNewResource(BaseResource):
    def get(self):
        #org_id=self.current_org.id
        result = models.ContractApply.get_id()
        return result[0]

    @require_admin_default
    def post(self):
        req = request.get_json(force=True)
        require_fields(req, ("code","name"))
        contractapply = models.ContractApply(
        id=req["id"],
        org=self.current_org,
        userid=req["userid"],
        bill_date = req["bill_date"],
        employeeid = req["employeeid"],
        departmentid =req["departmentid"],
        code = req["code"],
        name = req["name"],
        type = req["type"],
        party_aid = req["party_aid"],
        party_bid = req["party_bid"],
        party_cid = req["party_cid"],
        pay_direction =req["pay_direction"],
        pricetype =req["pricetype"],
        sign_date = req["sign_date"],
        start_date = req["start_date"],
        end_date = req["end_date"],
        amount = req["amount"],
        amount_words = req["amount_words"],
        status =req["status"],
        message =req["message"],
        )

        try:
            models.db.session.add(contractapply)
            models.db.session.commit()
        except IntegrityError as e:
            if "code" in str(e):
                abort(400, message="编号已存在.")
            abort(500)

        # timeserial.record_event(
        #     {"action": "create", "object_id": timeserial.id, "object_type": "timeserial"}
        # )
class ContractApplycodeResource(BaseResource):
    def post(self):
        req = request.get_json(force=True)
        tblname = req["tblname"]
        type = req["type"]
        bill_date = req["bill_date"]
        tblfield = req["tblfield"]
        userid = req["userid"] if "userid" in req else 0
        org_id =self.current_org.id
        result = models.ContractApply.get_code(tblname,type,tblfield,bill_date,org_id,userid)
        return result[0]

class ContractApplyResource(BaseResource):
    def get(self, contractapply_id):
        result = models.ContractApply.get_by_id(contractapply_id)
        return result.to_dict()

    @require_admin_default
    def post(self, contractapply_id):
        req = request.get_json(force=True)
        require_fields(req, ("code","name"))

        contractapply = models.ContractApply.get_by_id(contractapply_id)
        params = dict(bill_date=req["bill_date"], employeeid=req["employeeid"], departmentid=req["departmentid"], code=req["code"],
                name=req["name"],type=req["type"],party_aid=req["party_aid"],party_bid=req["party_bid"],party_cid=req["party_cid"],pricetype =req["pricetype"],
                pay_direction=req["pay_direction"],sign_date=req["sign_date"],start_date=req["start_date"],end_date=req["end_date"],amount=req["amount"],
                amount_words=req["amount_words"],message=req["message"])
        try:
            self.update_model(contractapply, params)
            models.db.session.commit()
        except IntegrityError as e:
            if "code" in str(e):
                abort(400, message="编号已存在.")
            abort(500)

class ContractApplydeleteResource(BaseResource):
    @require_admin_default
    def post(self, contractapply_id):
        contractapply =  models.ContractApply.get_by_id(contractapply_id)
        models.db.session.delete(contractapply)
        models.db.session.commit()

class ContractApplyListResource(BaseResource):
    def post(self):
        req = request.get_json(force=True)
        page = req["page"]
        page_size = req["pagesize"]
        code = req["code"]
        name = req["name"]
        party_a = req["party_a"]
        type = req["type"]
        userid = str(req["userid"])
        orderfield = req["field"] if "field" in req else ""
        if orderfield=="code" :
            orderfield ="t1.code"
        elif orderfield=="name":
            orderfield ="t1.name"
        elif orderfield=="partyaname":
            orderfield ="t2.strcustomername"
        elif orderfield=="typename":
            orderfield ="t4.typename"
        elif orderfield=="amount":
            orderfield ="t1.amount"
        else:
            orderfield ="t1.id"
        order = req["order"] if "order" in req else 0
        strwhere ="t1.org_id=" +str(self.current_org.id)
        if code !="" :
            strwhere = strwhere + " and t1.code like '%"+code+"%'"
        if name !='' :
            strwhere = strwhere + " and t1.name like '%"+name+"%'"
        if party_a !='' :
            strwhere = strwhere + " and t2.strcustomername like '%"+party_a+"%'"
        if type !='' :
            strwhere = strwhere + " and  '"+type+"' = ANY(t1.type)"
        if userid !='':
            strwhere = strwhere + """ and  exists(select orgpower_ids from public.users where id='""" + userid + """' 
            and (t1.departmentid=any(orgpower_ids) or 0=any(orgpower_ids)))"""

        strgetfield =""" t1.*,t2.strcustomername as partyaname,t3.strcustomername  as partybname,
                    case when t1.status=2 then '已审核' when t1.status=1 then '审核中' else '草稿' end strstatus,
                    t4.typename,COALESCE(t5.id,0) as contractsid,case when COALESCE(t5.id,0)=0 then false else true end blniscontract"""

        tblname = """public.contractapply t1 left join public.customertemp t2 on t1.party_aid=t2.id
                    left join public.customertemp t3 on t1.party_bid=t3.id left join
                    public.contracttypeview t4 on t1.type =t4.type  and t1.org_id=t4.org_id
        	        left join contracts t5 on t1.id=t5.sourceid and t5.sourcetype='contractapply'"""
        #orderfield ="t1.id"
        result = models.ContractApply.get_pagequery(tblname,strgetfield,orderfield,page_size,page,order,strwhere)
        return result[0]
#20200530合同申请单生成正式合同
class ContractPushBillResource(BaseResource):
    def post(self):
        req = request.get_json(force=True)
        sourcebill = req["sourcebill"]
        sourcebillid = req["sourcebillid"]
        bill = req["bill"]
        userid = req["userid"]
        typeid = req["typeid"]
        result = models.ContractApply.get_pushbill(sourcebill,sourcebillid,bill,userid,typeid)
        models.db.session.commit()
        return result[0]
